const router = require('koa-router')()
const query = require("../db/mysql");
const crypto = require('crypto');
const wxkey = require('../public/wxkey');
const koa2Req = require('koa2-request');
const {obj,encrypt, decrypt} = require('../public/util')
const {key,iv} = obj;

router.get('/mp-login', async (ctx, next) => {
  let auth_url = `https://api.weixin.qq.com/sns/jscode2session`
    + `?appid=${wxkey.appid}`
    + `&secret=${wxkey.secret}`
    + `&js_code=${ctx.query.code}`
    + `&grant_type=authorization_code`;
  let ret = await koa2Req(auth_url);
  const { session_key, openid } = JSON.parse(ret.body);
  let tok = encrypt(openid, key, iv);
  ctx.body = tok;
})

router.post('/uInformation',async(ctx,next)=>{
  console.log(ctx.request.body);
  const {token,nickName,avatarUrl} = ctx.request.body;
  console.log(token);
  let uId = decrypt(token,key,iv);
  console.log(uId);
  try {
    let sql = `Insert into user(uId,uName,uImage) values(?,?,?)`;
    let data = await query(sql,[uId,nickName,avatarUrl]);
    console.log(data);
    return ctx.body = {
      status: 200,
      data: data,
      msg: ''
    }
  } catch (error) {
    console.log(error);
    return ctx.body = {
      status: 500,
      msg: error
    }
  }
})

module.exports = router;